package com.sj.purchase.modules.cost.config.task.synchronizedata;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sj.purchase.modules.cost.repository.stock.SkuStockRepository;
import com.sj.purchase.modules.cost.domain.stock.SkuStock;
import com.sj.purchase.modules.cost.domain.stock.SkuStockId;
import com.sj.purchase.util.StockUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * Created by yangrd on 2017/10/11
 **/
@Component
class StockTask2 {

    private static final Logger logger = LoggerFactory.getLogger(StockTask2.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SkuStockRepository skuStockRepository;

    @Value("${sj.ecwms}")
    private String ecwmsApi;

    @Transactional
    public Boolean synchronizeWmsStock() {
       return getStock(jsonArray->{
            Date now = new Date();
            List<SkuStock> list = jsonArray.stream().map(o -> (JSONObject) o).map(o -> {
                SkuStockId skuStockId = new SkuStockId();
                String warehouse = o.getString("warehouse");
                skuStockId.setWarehouse(StockUtils.getWarehouse(warehouse));
                skuStockId.setSkuNo(o.getString("skuNo"));
                skuStockId.setCreateDate(now);
                SkuStock skuStock = new SkuStock();
                skuStock.setId(skuStockId);
                skuStock.setNum(o.getLong("num"));
                skuStock.setCreateTime(now);
                return skuStock;
            }).filter(skuStock -> Objects.nonNull(skuStock.getId().getWarehouse())).collect(Collectors.toList());
            logger.debug("库存同步成本");
            skuStockRepository.save(list);
        },6*60*1000,6);

    }

    //TODO 调用美琳的备份数据

    /**
     *
     * @param callback 回调
     * @param millis 间隔时间
     * @param maxRequestNum 最大重複请求次数
     */
    private Boolean getStock(Consumer<JSONArray> callback, long millis,int maxRequestNum){
        try{
            String json = restTemplate.getForObject(ecwmsApi + "/inventory", String.class);
            callback.accept(JSONArray.parseArray(json));
            return true;
        }catch (HttpServerErrorException _504){
            logger.error("库存同步失敗");
            try {
                Thread.sleep(millis);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            maxRequestNum--;
            if(maxRequestNum>=0){
                getStock(callback,millis,maxRequestNum);
            }
        }
        return false;
    }
}
